package com.tledu.cyrus.web;

import com.alibaba.fastjson2.JSONObject;
import com.tledu.cyrus.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 根据用户输入的查询条件，进行响应的查询
 *
 * @author cyrus
 */
@WebServlet("/student1")
public class StudentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 一、获取请求信息
        // 1. 请求题的格式是json格式
        // 2. 请求参数包括name、age、sex、phone
        // 解决乱码问题
        req.setCharacterEncoding("utf-8");
        // 解析请求体中的参数
        // 1. 获取输入流
        BufferedReader reader = req.getReader();
        // 2. 获取请求的完整信息
        StringBuilder requestBodyJsonStr = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            requestBodyJsonStr.append(line);
        }
        // 3, 将字符串信息解析承json对象
        JSONObject params = JSONObject.parseObject(requestBodyJsonStr.toString());
        if (params == null) {
            params = new JSONObject();
        }


        // 二、进行业务逻辑处理，组装返回数据
        List<Student> studentList = new ArrayList<Student>();
        //  根据条件进行查询，组装sql语句
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/java34_student_manger",
                    "root",
                    "root"
            );
            String sql = "select * from student where 1=1 ";
            if (params.getString("name") != null && !params.getString("name").equals("")) {
                sql += " and name like ?";
            }
            if (params.getInteger("age") != null) {
                sql += " and age = ?";
            }
            if (params.getInteger("sex") != null) {
                sql += " and sex = ?";
            }
            if (params.getString("phone") != null && !params.getString("phone").isEmpty()) {
                sql += " and phone = ?";
            }

            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            int i = 1;
            if (params.getString("name") != null && !params.getString("name").equals("")) {
                preparedStatement.setString(i++, "%" + params.getString("name") + "%");
            }
            if (params.getInteger("age") != null) {
                preparedStatement.setInt(i++, params.getInteger("age"));
            }
            if (params.getInteger("sex") != null) {
                preparedStatement.setInt(i++, params.getInteger("sex"));
            }
            if (params.getString("phone") != null && !params.getString("phone").equals("")) {
                preparedStatement.setString(i++, params.getString("phone"));
            }
            // 执行sql
            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                studentList.add(new Student(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getInt("age"),
                        rs.getInt("sex"),
                        rs.getString("phone")
                ));
            }
            preparedStatement.close();
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }


        // 三、进行数据响应
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(JSONObject.toJSONString(studentList));
    }
}
